#include "ThreadPool.h"  
#include <string>  
#include <iostream>  
  
using namespace std;  
  
vector<pthread_t> ThreadPool::_busy_thread_vec;  
vector<pthread_t> ThreadPool::_idle_thread_vec;  
 
pthread_cond_t ThreadPool::_thread_cond = PTHREAD_COND_INITIALIZER;  
MutexLock			 ThreadPool::_thread_lock = MutexLock();
  
ThreadPool::ThreadPool(int num)  
{   
	_thread_num = num;  
	Create();  
}  

ThreadPool::~ThreadPool()
{
	
}

int ThreadPool::MoveToIdle(pthread_t tid)  
{  
	vector<pthread_t>::iterator busy_iter = _busy_thread_vec.begin();  
 	
	while( busy_iter != _busy_thread_vec.end() )  
	{  
		if ( tid == *busy_iter )  
		{  
			break;  
		}  
		busy_iter++;  
 }  
 
 _busy_thread_vec.erase(busy_iter);  
 _idle_thread_vec.push_back(tid);  
 
 return 0;  
}  
  
int ThreadPool::MoveToBusy(pthread_t tid)  
{ 
	vector<pthread_t>::iterator idle_iter = _idle_thread_vec.begin();  
	
	while ( idle_iter != _idle_thread_vec.end() )  
	{  
		if ( tid == *idle_iter )  
		{  
			break;  
		}  
		idle_iter++;  
	}  
	
	_idle_thread_vec.erase(idle_iter);  
	_busy_thread_vec.push_back(tid);  
	
	return 0;  
} 
 
void* ThreadPool::ThreadFunc(void * args)  
{  
	pthread_t tid = pthread_self();  
	
	while(true)  
	{  
		_thread_lock.Lock();
    
		pthread_cond_wait( &_thread_cond , _thread_lock.GetMutex() ); 
		cout << "tid:" << tid << " run" << endl; 
   
		//get task  
		vector<ITask*>* task_vec = (vector<ITask*>*)args; 
		 
		vector<ITask*>::iterator iter = task_vec->begin();  
			
		while(iter != task_vec->end())  
		{  
			MoveToBusy(tid);  
			break;  
		} 

		ITask* task = *iter;  
		task_vec->erase(iter);  
		
		_thread_lock.UnLock();  
		
  //cout << "idel thread number:" << CThreadPool::m_vecIdleThread.size() << endl;  
  //cout << "busy thread number:" << CThreadPool::m_vecBusyThread.size() << endl;  
  //cout << "task to be run:" << taskList->size() << endl;  
		task->Exec();
		
		delete task;  
    
  //cout << "CThread::thread work" << endl;  
		cout << "tid:" << tid << " idle" << endl;      
	}
	  
	return (void*)0;  
}  
  
int ThreadPool::AddTask(ITask *task)  
{  
	_task_vec.push_back(task);  
	
	pthread_cond_signal(&_thread_cond);  
	
	return 0;  
}
  
int ThreadPool::Create()  
{  
	for(int i = 0; i < _thread_num;i++)  
	{  
		pthread_t tid = 0;  
		pthread_create(&tid,NULL,ThreadFunc,&_task_vec); 
		 
		_idle_thread_vec.push_back(tid);  
	}  
	
	return 0;  
}  
  
int ThreadPool::StopAll()  
{  
	vector<pthread_t>::iterator iter = _idle_thread_vec.begin();  
		
	while( iter != _idle_thread_vec.end() )  
	{  
		pthread_cancel(*iter);  
		pthread_join(*iter,NULL);  
		iter++;  
	}  
  
	iter = _busy_thread_vec.begin();  
	while(iter != _busy_thread_vec.end())  
	{  
		pthread_cancel(*iter);  
		pthread_join(*iter,NULL);  
		iter++;  
	}  
   
	return 0;  
	
} 
